package com.imooc.sell.service.impl;

import com.imooc.sell.Enums.ProductInfoEnum;
import com.imooc.sell.Enums.ResultEnum;
import com.imooc.sell.dataobject.ProductInfo;
import com.imooc.sell.dto.CarTo;
import com.imooc.sell.exception.SellException;
import com.imooc.sell.repository.ProductInfoRepository;
import com.imooc.sell.service.ProductInfoService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;

/**
 * @Author 小柯
 * @Date 2019/6/29  18:41
 **/
@Service
public class ProductInfoServiceImpl implements ProductInfoService {

    @Autowired
    private ProductInfoRepository repository;

    @Override
    public ProductInfo findOne(String productId) {
        return repository.findOne(productId);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return repository.findByProductStatus(ProductInfoEnum.UP.getCode());
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        return repository.findAll(pageable);
    }

    @Override
    public ProductInfo save(ProductInfo productInfo) {
        return repository.save(productInfo);
    }


    /** 减库存 */
    @Override
    @Transactional
    public void increaseStock(List<CarTo> carToList) {
        for (CarTo carTo : carToList) {
            ProductInfo productInfo = repository.findOne(carTo.getProductId());
            if(productInfo == null){
                throw  new SellException(ResultEnum.PRODUCT_NOE_EXIST);
            }

            Integer result = productInfo.getProductStock() + carTo.getProductQuantity();
 /*           if(result < 0){
                throw new SellException(ResultEnum.PRODUCT_STOCK_INVENTORY);
            }*/
            productInfo.setProductStock(result);
            repository.save(productInfo);
        }


    }

    @Override
    @Transactional
    public void decreaseStock(List<CarTo> carToList) {

        for (CarTo carTo : carToList) {
            ProductInfo productInfo = repository.findOne(carTo.getProductId());
            if(productInfo == null){
                throw  new SellException(ResultEnum.PRODUCT_NOE_EXIST);
            }

           Integer result = productInfo.getProductStock() - carTo.getProductQuantity();
            if(result < 0){
                throw new SellException(ResultEnum.PRODUCT_STOCK_INVENTORY);
            }
            productInfo.setProductStock(result);
            repository.save(productInfo);
        }
    }


}
